<template>
	<view class="container">
		<uni-card :title="isEdit ? '编辑阀门' : '添加阀门'" :is-shadow="true" margin="20rpx" class="full-height-card">
			<view class="card-content">
				<uni-forms ref="valveForm" :model="valveData" :rules="rules" validate-trigger="submit" label-position="top" label-width="auto">
					<!-- 标识信息 -->
					<uni-section title="标识信息" type="line" padding>
						<view class="form-section">
							<view class="form-item">
								<text class="form-label required">阀门编号</text>
								<uni-easyinput class="form-input" v-model="valveData.id" placeholder="请输入阀门编号" :disabled="isEdit" name="id" />
								<text v-if="errors.id" class="error-message">{{errors.id}}</text>
							</view>
							
							<view class="form-item">
								<text class="form-label required">阀门名称</text>
								<uni-easyinput class="form-input" v-model="valveData.name" placeholder="请输入阀门名称" name="name" />
								<text v-if="errors.name" class="error-message">{{errors.name}}</text>
							</view>
							
							<view class="form-item">
								<text class="form-label required">设备类型</text>
								<uni-data-select class="form-input" v-model="valveData.type" :localdata="valveTypes" placeholder="请选择设备类型" name="type" />
								<text v-if="errors.type" class="error-message">{{errors.type}}</text>
							</view>
							
							<view class="form-item">
								<text class="form-label required">使用状态</text>
								<uni-data-select class="form-input" v-model="valveData.status" :localdata="valveStatus" placeholder="请选择使用状态" name="status" />
								<text v-if="errors.status" class="error-message">{{errors.status}}</text>
							</view>
						</view>
					</uni-section>
					
					<!-- 技术规格参数 -->
					<uni-section title="技术规格参数" type="line" padding>
						<view class="form-section">
							<view class="form-item">
								<text class="form-label required">型号规格</text>
								<uni-easyinput class="form-input" v-model="valveData.model" placeholder="请输入型号规格" name="model" />
								<text v-if="errors.model" class="error-message">{{errors.model}}</text>
							</view>
							
							<view class="form-item">
								<text class="form-label required">口径(mm)</text>
								<uni-easyinput class="form-input" v-model="valveData.diameter" placeholder="请输入口径" type="number" name="diameter" />
								<text v-if="errors.diameter" class="error-message">{{errors.diameter}}</text>
							</view>
							
							<view class="form-item">
								<text class="form-label required">阀体材质</text>
								<uni-data-select class="form-input" v-model="valveData.material" :localdata="valveMaterials" placeholder="请选择阀体材质" name="material" />
								<text v-if="errors.material" class="error-message">{{errors.material}}</text>
							</view>
							
							<view class="form-item">
								<text class="form-label required">压力等级</text>
								<uni-easyinput class="form-input" v-model="valveData.pressureLevel" placeholder="请输入压力等级" name="pressureLevel" />
								<text v-if="errors.pressureLevel" class="error-message">{{errors.pressureLevel}}</text>
							</view>
							
							<view class="form-item">
								<text class="form-label required">驱动方式</text>
								<uni-data-select class="form-input" v-model="valveData.drivingMode" :localdata="drivingModes" placeholder="请选择驱动方式" name="drivingMode" />
								<text v-if="errors.drivingMode" class="error-message">{{errors.drivingMode}}</text>
							</view>
						</view>
					</uni-section>
					
					<!-- 安装位置信息 -->
					<uni-section title="安装位置信息" type="line" padding>
						<view class="form-section">
							<view class="form-item">
								<text class="form-label required">安装区域</text>
								<uni-easyinput class="form-input" v-model="valveData.area" placeholder="请输入安装区域" name="area" />
								<text v-if="errors.area" class="error-message">{{errors.area}}</text>
							</view>
							
							<view class="form-item">
								<text class="form-label required">具体位置</text>
								<uni-easyinput class="form-input" v-model="valveData.location" placeholder="请输入具体位置" name="location" />
								<text v-if="errors.location" class="error-message">{{errors.location}}</text>
							</view>
							
							<view class="form-item">
								<text class="form-label required">管网位置</text>
								<uni-easyinput class="form-input" v-model="valveData.networkLocation" placeholder="请输入管网位置" name="networkLocation" />
								<text v-if="errors.networkLocation" class="error-message">{{errors.networkLocation}}</text>
							</view>
							
							<view class="form-item">
								<text class="form-label required">安装日期</text>
								<uni-datetime-picker class="form-input" type="date" v-model="valveData.installDate" placeholder="请选择安装日期" name="installDate" />
								<text v-if="errors.installDate" class="error-message">{{errors.installDate}}</text>
							</view>
						</view>
					</uni-section>
					
					<!-- 制造商与供应商信息 -->
					<uni-section title="制造商与供应商信息" type="line" padding>
						<view class="form-section">
							<view class="form-item">
								<text class="form-label required">制造商</text>
								<uni-easyinput class="form-input" v-model="valveData.manufacturer" placeholder="请输入制造商" name="manufacturer" />
								<text v-if="errors.manufacturer" class="error-message">{{errors.manufacturer}}</text>
							</view>
							
							<view class="form-item">
								<text class="form-label">供应商</text>
								<uni-easyinput class="form-input" v-model="valveData.supplier" placeholder="请输入供应商" name="supplier" />
								<text v-if="errors.supplier" class="error-message">{{errors.supplier}}</text>
							</view>
							
							<view class="form-item">
								<text class="form-label">联系人</text>
								<uni-easyinput class="form-input" v-model="valveData.contact" placeholder="请输入联系人" name="contact" />
								<text v-if="errors.contact" class="error-message">{{errors.contact}}</text>
							</view>
							
							<view class="form-item">
								<text class="form-label">联系电话</text>
								<uni-easyinput class="form-input" v-model="valveData.contactPhone" placeholder="请输入联系电话" name="contactPhone" />
								<text v-if="errors.contactPhone" class="error-message">{{errors.contactPhone}}</text>
							</view>
						</view>
					</uni-section>
					
					<view class="form-actions">
						<button type="primary" @click="submitForm">保存</button>
						<button type="default" @click="goBack">取消</button>
					</view>
				</uni-forms>
			</view>
		</uni-card>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isEdit: false,
				valveId: '',
				valveData: {
					id: '',
					name: '',
					type: '',
					status: '正常',
					model: '',
					diameter: '',
					material: '',
					pressureLevel: '',
					drivingMode: '',
					area: '',
					location: '',
					networkLocation: '',
					installDate: this.formatDate(new Date()),
					manufacturer: '',
					supplier: '',
					contact: '',
					contactPhone: ''
				},
				
				// 下拉选项数据
				valveTypes: [
					{ value: '闸阀', text: '闸阀' },
					{ value: '蝶阀', text: '蝶阀' },
					{ value: '球阀', text: '球阀' },
					{ value: '截止阀', text: '截止阀' },
					{ value: '止回阀', text: '止回阀' },
					{ value: '调节阀', text: '调节阀' }
				],
				valveStatus: [
					{ value: '正常', text: '正常' },
					{ value: '维护中', text: '维护中' },
					{ value: '故障', text: '故障' },
					{ value: '停用', text: '停用' }
				],
				valveMaterials: [
					{ value: '不锈钢', text: '不锈钢' },
					{ value: '球墨铸铁', text: '球墨铸铁' },
					{ value: '碳钢', text: '碳钢' },
					{ value: '铜合金', text: '铜合金' },
					{ value: '塑料', text: '塑料' }
				],
				drivingModes: [
					{ value: '手动', text: '手动' },
					{ value: '电动', text: '电动' },
					{ value: '气动', text: '气动' },
					{ value: '液动', text: '液动' }
				],
				
				// 模拟阀门列表数据
				valveList: [
					{
						id: 'V001',
						name: '进水主阀',
						type: '闸阀',
						status: '正常',
						model: 'Z45X-16Q',
						diameter: 200,
						material: '球墨铸铁',
						pressureLevel: 'PN16',
						drivingMode: '手动',
						area: '水厂一区',
						location: '进水泵房东侧',
						networkLocation: '主管网节点A12',
						installDate: '2022-05-15',
						manufacturer: '上海XX阀门制造有限公司',
						supplier: '北京XX设备有限公司',
						contact: '张工',
						contactPhone: '13812345678'
					},
					{
						id: 'V002',
						name: '出水控制阀',
						type: '蝶阀',
						status: '维护中',
						model: 'D343H-16C',
						diameter: 150,
						material: '不锈钢',
						pressureLevel: 'PN10',
						drivingMode: '电动',
						area: '水厂二区',
						location: '出水泵房西侧',
						networkLocation: '配水管网节点B08',
						installDate: '2022-06-20',
						manufacturer: '北京XX阀门制造有限公司',
						supplier: '北京XX设备有限公司',
						contact: '李工',
						contactPhone: '13987654321'
					},
					{
						id: 'V003',
						name: '旁通控制阀',
						type: '球阀',
						status: '故障',
						model: 'Q41F-16P',
						diameter: 100,
						material: '不锈钢',
						pressureLevel: 'PN16',
						drivingMode: '气动',
						area: '水厂三区',
						location: '配水间南侧',
						networkLocation: '支管网节点C05',
						installDate: '2022-07-10',
						manufacturer: '天津XX阀门制造有限公司',
						supplier: '天津XX设备有限公司',
						contact: '王工',
						contactPhone: '13756781234'
					}
				],
				
				// 表单验证规则
				rules: {
					id: {
						rules: [
							{ required: true, errorMessage: '请输入阀门编号' }
						]
					},
					name: {
						rules: [
							{ required: true, errorMessage: '请输入阀门名称' }
						]
					},
					type: {
						rules: [
							{ required: true, errorMessage: '请选择设备类型' }
						]
					},
					status: {
						rules: [
							{ required: true, errorMessage: '请选择使用状态' }
						]
					},
					model: {
						rules: [
							{ required: true, errorMessage: '请输入型号规格' }
						]
					},
					diameter: {
						rules: [
							{ required: true, errorMessage: '请输入口径' },
							{ format: 'number', errorMessage: '口径必须是数字' }
						]
					},
					material: {
						rules: [
							{ required: true, errorMessage: '请选择阀体材质' }
						]
					},
					pressureLevel: {
						rules: [
							{ required: true, errorMessage: '请输入压力等级' }
						]
					},
					drivingMode: {
						rules: [
							{ required: true, errorMessage: '请选择驱动方式' }
						]
					},
					area: {
						rules: [
							{ required: true, errorMessage: '请输入安装区域' }
						]
					},
					location: {
						rules: [
							{ required: true, errorMessage: '请输入具体位置' }
						]
					},
					networkLocation: {
						rules: [
							{ required: true, errorMessage: '请输入管网位置' }
						]
					},
					installDate: {
						rules: [
							{ required: true, errorMessage: '请选择安装日期' }
						]
					},
					manufacturer: {
						rules: [
							{ required: true, errorMessage: '请输入制造商' }
						]
					}
				},
				
				// 存储错误信息
				errors: {}
			}
		},
		onLoad(options) {
			if (options.mode === 'edit' && options.id) {
				this.isEdit = true;
				this.valveId = options.id;
				this.loadValveData();
			} else if (options.mode === 'add') {
				this.isEdit = false;
				this.initNewValve();
			}
		},
		methods: {
			loadValveData() {
				// 在实际应用中，这里应该通过API获取阀门数据
				// 这里使用模拟数据
				const valve = this.valveList.find(v => v.id === this.valveId);
				
				if (valve) {
					this.valveData = JSON.parse(JSON.stringify(valve));
				} else {
					uni.showToast({
						title: '阀门数据不存在',
						icon: 'none'
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				}
			},
			initNewValve() {
				// 初始化一个新阀门
				this.valveData = {
					id: 'V' + this.generateValveId(),
					name: '',
					type: '',
					status: '正常',
					model: '',
					diameter: '',
					material: '',
					pressureLevel: '',
					drivingMode: '',
					area: '',
					location: '',
					networkLocation: '',
					installDate: this.formatDate(new Date()),
					manufacturer: '',
					supplier: '',
					contact: '',
					contactPhone: ''
				};
			},
			submitForm() {
				// 重置错误信息
				this.errors = {};
				
				this.$refs.valveForm.validate().then(res => {
					if (res.valid) {
						// 表单验证通过
						uni.showLoading({
							title: '保存中...'
						});
						
						// 模拟保存操作
						setTimeout(() => {
							uni.hideLoading();
							
							// 返回上一页并传递数据
							uni.navigateBack({
								success: () => {
									// 获取页面实例
									const pages = getCurrentPages();
									const prevPage = pages[pages.length - 2]; // 上一个页面
									
									// 更新上一个页面的数据
									if (prevPage && prevPage.$vm) {
										// 在实际项目中，这里应该调用API保存数据
										// 然后通知列表页刷新数据，而不是直接修改内存中的数据
										
										// 这里只是模拟
										if (this.isEdit) {
											// 编辑模式
											const index = prevPage.$vm.valveList.findIndex(v => v.id === this.valveData.id);
											if (index !== -1) {
												prevPage.$vm.valveList.splice(index, 1, this.valveData);
											}
										} else {
											// 添加模式
											prevPage.$vm.valveList.push(this.valveData);
										}
										
										// 显示成功提示
										uni.showToast({
											title: this.isEdit ? '编辑成功' : '添加成功',
											icon: 'success'
										});
									}
								}
							});
						}, 1000);
					} else {
						// 表单验证失败，收集错误信息
						this.errors = {};
						Object.keys(res.errors).forEach(key => {
							this.errors[key] = res.errors[key][0].errorMessage;
						});
					}
				}).catch(err => {
					console.log('表单验证失败:', err);
				});
			},
			goBack() {
				uni.navigateBack();
			},
			// 生成阀门ID（实际应用中应从后端获取）
			generateValveId() {
				// 查找现有ID中的最大数字
				let maxNum = 0;
				this.valveList.forEach(valve => {
					const num = parseInt(valve.id.replace(/\D/g, ''));
					if (num > maxNum) {
						maxNum = num;
					}
				});
				
				// 生成新ID
				return (maxNum + 1).toString().padStart(3, '0');
			},
			// 格式化日期
			formatDate(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				return `${year}-${month}-${day}`;
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
		height: 100%;
	}
	
	.container {
		padding-bottom: 0;
		min-height: 100vh;
	}
	
	.full-height-card {
		min-height: calc(100vh - 140rpx);
		margin-bottom: 0 !important;
		box-shadow: none !important;
		
		:deep(.uni-card__content) {
			padding-bottom: 50rpx;
		}
	}
	
	.card-content {
		padding: 10rpx 0;
	}
	
	.form-section {
		background-color: #fff;
		border-radius: 8rpx;
	}
	
	.form-item {
		display: flex;
		flex-direction: column;
		padding: 20rpx 0;
	}
	
	.form-label {
		font-size: 28rpx;
		color: #606266;
		margin-bottom: 10rpx;
	}
	
	.required:before {
		content: '*';
		color: #dd524d;
		margin-right: 4rpx;
	}
	
	.form-input {
		width: 100%;
	}
	
	.error-message {
		font-size: 24rpx;
		color: #dd524d;
		margin-top: 8rpx;
	}
	
	.form-actions {
		display: flex;
		justify-content: space-between;
		padding: 40rpx 20rpx 20rpx;
		
		button {
			width: 45%;
		}
	}
</style> 